#!/bin/sh /etc/rc.common
# Copyright (C) 2016 chenhw2 <chenhw2@github.com>
# Copyright (C) 2018 Ycarus (Yannick Chabanois) <ycarus@zugaina.org>

START=85

USE_PROCD=1
PROG_NAME=haproxy
PROG=/usr/sbin/${PROG_NAME}

PIDCOUNT=0

_log() {
	logger -p daemon.info -t ${PROG_NAME} "$@"
}

_err() {
	logger -p daemon.err -t ${PROG_NAME} "$@"
}

validate_section() {
	uci_validate_section haproxy-tcp general "${1}" \
		'enable:bool:0'            \
		'retries:uinteger:3'       \
		'timeout:uinteger:4000'    \
		'startup_delay:uinteger:5' \
		'admin_stats:port:7777'    \
		'listen:string'            \
		'upstreams:list(string)'
}

genline_srv(){
	line="$1"
	hash="$(echo -n $line | md5sum | cut -c1-6)"
	hash="$(echo -n $line | tr -d '\t ' | cut -c1-8)__$hash"
	echo "    server $hash  $line" | tr -d "\'"
}

boot() {
	local delay=$(uci -q get $NAME.general.startup_delay)
	(sleep ${delay:-0} && start >/dev/null 2>&1) &
	return 0
}

start_instance() {
	local enable retries timeout admin_stats startup_delay listen upstreams

	validate_section "${1}" || {
		_err "validation failed"
		return 1
	}

	[ "$enable" = 1 ] || return 1

	PIDCOUNT="$(( ${PIDCOUNT} + 1))"

	mkdir -p /var/etc
	cat <<-EOF > /var/etc/$PROG_NAME.cfg
	global
	    nbproc $(grep -c '^processor' /proc/cpuinfo | tr -d "\n")

	defaults
	    mode tcp
	    retries ${retries}
	    timeout connect ${timeout}
	    timeout client ${timeout}
	    timeout server ${timeout}

	listen admin_stats
	    bind 0.0.0.0:${admin_stats}
	    mode http
	    stats uri /
	    stats refresh 10s

	frontend tcp-in
	    bind ${listen:-0.0.0.0:6666}
	    default_backend tcp-out

	backend tcp-out
		$(	if [ 0 -lt $(grep -c weight /etc/config/haproxy-tcp) ]; then
				echo "    balance static-rr"
				sed -n 's/.*upstreams[\t ]*//p' /etc/config/haproxy-tcp |
				while read upstream; do
					genline_srv "$upstream"
				done
			else
				config_list_foreach "${1}" "upstreams" genline_srv
			fi
		)

EOF

	procd_open_instance
	procd_set_param command ${PROG} \
		-q -D -f /var/etc/$PROG_NAME.cfg \
		-p /var/run/${PROG_NAME}.${PIDCOUNT}.pid
	
	procd_set_param respawn 0 30 0
	procd_set_param stdout 1
	procd_set_param stderr 1
	
	procd_close_instance
}

start_service() {
	config_load haproxy-tcp
	config_foreach start_instance general
}

stop_service() {
	killall $PROG_NAME
	rm -rf /var/etc/$PROG_NAME.cfg
}

service_triggers() {
	procd_add_reload_trigger haproxy-tcp
}
